package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiDuProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.controller.admin.WebSocketServer;
import com.sky.utils.BaiDuUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author chengjy
 * @date 2023/4/24
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiDuProperties baiDuProperties;

    @Autowired
    private BaiDuUtil baiDuUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //发送接单请求给浏览器
        Map map = new HashMap<>();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        log.info("发送接单请求：{}",outTradeNo);
    }

    /**
     * 查询历史订单
     *
     * @param ordersPage
     * @return
     */
    @Override
    public Result<PageResult> selectHistoryOrder(OrdersPageQueryDTO ordersPage) {
        PageHelper.startPage(ordersPage.getPage(),ordersPage.getPageSize());
        Page<OrderVO> page =  this.orderMapper.selectList(ordersPage);
        PageResult pageResult =  new PageResult(page.getTotal(),page.getResult());
        return Result.success(pageResult);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public Result<Orders> getByIdOrders(Long id) {
        Orders orders =  this.orderMapper.getByIdOrders(id);
        return Result.success(orders);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        //1、先根据id查询订单，并判断订单状态是否已支付
        Orders orders = this.orderMapper.getByIdOrders(id);
        if(ObjectUtils.isEmpty(orders))throw new BaseException("订单不存在");
        Integer payStatus = orders.getPayStatus();
        if(payStatus == 1){
            //进行退款
            payStatus = 2;
        }
        //2、修改订单状态
        orders.setPayStatus(payStatus);
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //1. 根据id查询订单详情
        List<OrderDetail> detailList =  orderDetailMapper.getByOrderID(id);
        //2. 将订单详情全部加入购物车
        //2.1、使用stream遍历封装购物车集合实体
        List<ShoppingCart> list = detailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            return shoppingCart;
        }).collect(Collectors.toList());
        //2.2、批量添加购物车数据
        this.shoppingCartMapper.batchAddList(list);
    }

    /**
     * 订单搜索
     *
     * @param queryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(),queryDTO.getPageSize());
        //1、查询订单集合
        Page<OrderVO> orderVOS = this.orderMapper.selectList(queryDTO);
        //2、将菜品名称和数量做字符串拼接
        List<OrderVO> list = orderVOS.getResult();
        for (OrderVO orderVO : list) {
            String orderDish = orderVO.getOrderDetailList().stream().map(orderDetail -> {
                //2.2 菜名 * num
                String name = orderDetail.getName() + "*" + orderDetail.getNumber();
                return name;
            }).collect(Collectors.joining(""));
            //2.3、赋值
            orderVO.setOrderDishes(orderDish);
        }
        return new PageResult(orderVOS.getTotal(),orderVOS.getResult());
    }

    /**
     * 订单状态数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //1、数据库查询个状态数量
        return this.orderMapper.selectStatistics();
    }

    /**
     * 订单搜索
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetailsInfo(Long id) {
        OrderVO orderVOS = this.orderMapper.selectInfo(id);
        List<OrderDetail> detailList = orderVOS.getOrderDetailList();
        String orderDishs = detailList.stream().map(detail -> {
            String dishName = detail.getName() + "*" + detail.getNumber();
            return dishName;
        }).collect(Collectors.joining(""));
        orderVOS.setOrderDishes(orderDishs);
        return orderVOS;
    }

    /**
     * 拒单
     *
     * @param dto
     * @return
     */
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        //封装实体
        Orders orders = Orders.builder()
                .id(dto.getId())
                .rejectionReason(dto.getRejectionReason())
                .status(6)
                .payStatus(2)
                .cancelTime(LocalDateTime.now())
                .build();
        //修改
        this.orderMapper.update(orders);
    }

    /**
     * 接单
     *
     * @param orders
     */
    @Override
    public void confirm(Orders orders) {
        //封装实体
        orders.setStatus(Orders.CONFIRMED);
        //修改
        this.orderMapper.update(orders);
    }

    /**
     * 派送
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getByIdOrders(id);
        //封装实体
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        //修改
        this.orderMapper.update(orders);
    }

    /**
     * 完成
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getByIdOrders(id);
        //封装实体
        orders.setStatus(Orders.COMPLETED);
        //修改
        this.orderMapper.update(orders);
    }

    /**
     * 取消
     *
     * @param dto
     */
    @Override
    public void cancel(OrdersCancelDTO dto) {
        //封装实体
        Orders orders = Orders.builder()
                .id(dto.getId())
                .cancelReason(dto.getCancelReason())
                .status(6)
                .payStatus(2)
                .cancelTime(LocalDateTime.now())
                .build();
        //修改
        this.orderMapper.update(orders);
    }

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
        //1、校验收货地址/购物车菜品 是否存在
        //1.1、购物车
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> shoppingCarts = this.shoppingCartMapper.selectList(shoppingCart);
        if(ObjectUtils.isEmpty(shoppingCarts)){
            throw new DeletionNotAllowedException("购物车为空");
        }
        //1.2、地址簿
        AddressBook addressBook = this.addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(ObjectUtils.isEmpty(addressBook)){
            throw new DeletionNotAllowedException("地址不存在为空");
        }
        //0.1判断地址和商家地址距离是否超过派送距离（5KM）
        Integer num;
        try{
            //派送地址
            String detail = addressBook.getDetail();
            String location1 = baiDuUtil.getLocation(detail);
            //商家地址
            String address = baiDuProperties.getAddress();
            String location2 = baiDuUtil.getLocation(address);
            //调用计算距离
            num = baiDuUtil.getDistances(location1, location2);
        }catch (Exception e){
            throw new BaseException("地址不合法，解析异常");
        }
        if(num != null && num > 5){
            throw new BaseException("超过商家派送距离，无法下单");
        }

        //2、组装orders 实体信息，入表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //2.1、订单号生成
        User user =  userMapper.getById(userId);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.PAID);
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //2.2、数据入表Orders
        this.orderMapper.save(orders);
        //3、将购物车数据全部加入到 OrderDetail表，并清空购物车
        List<OrderDetail> detailList = new ArrayList<>();
        shoppingCarts.forEach(cart ->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            detailList.add(orderDetail);
        });
        //3.1、批量新增
        this.orderDetailMapper.saveList(detailList);
        //3.2、清空购物车
        this.shoppingCartMapper.delete(userId);
        //4、组装OrderSubmitVO实体，返回
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        return orderSubmitVO;
    }
}
